<template>
    <el-tree
        default-expand-all 
        class="custom-tree" 
        :data="allFuncsTreeData" 
        :props="{ children: 'children' }"
        :expand-on-click-node="false">
        <template #default="{ data, data: { func_id, func_name, func_key, childred } }">
            <div class="custom-tree-node">
                <span>
                    <el-icon v-if="func_key !== ''" :size="20" color="#337ecc"><Paperclip /></el-icon>
                    {{func_name}}
                </span>
                <span>
                    <el-button text v-if="func_key === ''" @click="beginAdd(data)" :icon="Plus" type="success">add</el-button>
                    <el-button text v-if="![0, 1, 2].includes(func_id)" @click="beginUpdate(data)" :icon="Edit" type="warning">update</el-button>
                    <el-button text v-if="![0, 1, 2].includes(func_id)" :disabled="func_key === '' && childred" @click="removeHandler(func_id)" :icon="Delete" type="danger">delete</el-button>
                </span>
            </div>
        </template>
    </el-tree>
    <!-- 弹层 -->
    <el-dialog
        v-model="isEdit" title="功能编辑" width="30%" align-center>
        <el-form>
            <el-form-item label="功能类型">
                <el-radio-group v-model="isLeaf" :disabled="model.func_id !== 0 && model.func_key === '' && func.allFuncs.some(item => item.func_fid === model.func_id) ">
                    <el-radio :label="false">非叶子节点</el-radio>
                    <el-radio :label="true">叶子节点</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="父级功能">
               <el-cascader
                    :disabled="model.func_fid === 0"
                    v-model="model.func_fid"
                    :options="noLeafFuncsTreeData"
                    :props="{label:'func_name',value:'func_id',children:'children',checkStrictly:true,emitPath:false}">
               </el-cascader>
            </el-form-item>
            <el-form-item label="功能名称">
                <el-input v-model="model.func_name" placeholder="请输入功能名称..."></el-input>
            </el-form-item>
            <el-form-item label="功能对应组件" v-if="isLeaf">
                <el-select v-model="model.func_key">
                    <el-option label="- 请选择 -" value=""></el-option>
                    <el-option v-for="item in Object.keys(dashboard.funcMap)" :key="item" :value="item" :label="item"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="save">确定</el-button>
        <el-button @click="isEdit = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
    import { onMounted, ref, computed, reactive, watch } from 'vue';
    import { FuncApi } from "@/api";
    import { ElMessage, ElMessageBox } from 'element-plus';
    import { useDashboard, useFunc } from "@/store";
    import arrayToTree from '@/utils/arrayToTree';
    import {Plus,Edit,Delete, Paperclip} from '@element-plus/icons-vue';

    const dashboard = useDashboard();
    const func = useFunc();
    const isEdit = ref<boolean>(false);
    const isLeaf = ref<boolean>(false);
    const model = reactive<HttpPayload.Func>({ func_id: 0, func_name: "", func_key: "", func_fid: -1 });

    const allFuncsTreeData = computed<Vm.FuncNode[]>(() => {
       return [{func_id: 0, func_name: "RooT", func_key: "", func_fid: -1,
            children: arrayToTree(func.allFuncs,'func_id','func_fid')
        }];
    });

    const noLeafFuncsTreeData = computed<Vm.FuncNode[]>(() => {
       return [{func_id: 0, func_name: "RooT", func_key: "", func_fid: -1,
            children: arrayToTree(func.allFuncs.filter(item => item .func_key === '' ),'func_id','func_fid')
        }];
    });

    watch(isLeaf, newValue => {
        if(!newValue) model.func_key = "";
    })

    onMounted(async () => {
        try {
            func.allFuncs = await FuncApi.getAll()
        }catch(e) {/**/}
    })

    const removeHandler = async (func_id: number) => {
        try{
            await ElMessageBox.confirm(
            '真的要删除这个功能吗？',
            'warning',
            {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            }
        )
        await FuncApi.remove(func_id);
        await func.allFuncs.splice(func.allFuncs.findIndex(item => item.func_id === func_id), 1);
            ElMessage({
                type: 'success',
                message: '功能删除成功'
            })
        }catch(e) {/**/}
        
    };
    const beginAdd = (func: Vm.FuncNode) => {
        model.func_id = 0;
        model.func_name = "";
        model.func_key = "";
        model.func_fid = func.func_id;
        isEdit.value = false;

        isEdit.value = true
    };
    const beginUpdate = (func: Vm.FuncNode) => {
        model.func_id = func.func_id;
        model.func_name = func.func_name;
        model.func_key = func.func_key;
        model.func_fid = func.func_fid;
        isEdit.value = func.func_key !== "";

        isEdit.value = true;
    };
    const save = async () => {
        try{
            if(model.func_id === 0) {
                const func_id = await FuncApi.add(model);
                func.allFuncs.push({...model, func_id});
            }else {
                await FuncApi.update(model);
                const i = func.allFuncs.findIndex(item => item.func_id === model.func_id);
                func.allFuncs.splice(i,1,{...model});
            }
            isEdit.value = false;
            ElMessage({type:"success",message:"功能编辑成功"});
        }catch(e: any) {ElMessage({type:"error",message:e.message})}
    }
</script>

<style lang="stylus" scoped>
    .el-tree
        width 800px
        .custom-tree-node
            flex-grow 1
            display flex
            justify-content space-between
            align-items center
    .dialog-footer
        display: flex
        justify-content: center
    .el-icon
        vertical-align: middle
</style>